// 必须观看广告
var mustWatchAd = false;
var points = [];
// 跑步距离
var runningDistance = 0;
// 已经播放的距离(示例:您已经跑步100米.这里面会存100)
var playedDistances = [];
// 计算距离的位置集合
var distancePoints = [];
// 上次tip播放时间
var lastTipPlayTime = new Date().getTime();

// tip间隔时间(毫秒)
var tipPlayCyclePeriord = 30 * 1000;

// 运动提示
var runningTips = ["tip1.mp3", "tip2.mp3", "tip3.mp3", "tip4.mp3", "tip5.mp3", "tip6.mp3"]
// 腾讯地图对象
var mapContext = wx.createMapContext("map");
let index = 0;
const innerAudioContext = wx.createInnerAudioContext({
    useWebAudioImplement: true // 是否使用 WebAudio 作为底层音频驱动，默认关闭。对于短音频、播放频繁的音频建议开启此选项，开启后将获得更优的性能表现。由于开启此选项后也会带来一定的内存增长，因此对于长音频建议关闭此选项
})
// 激励视频
let rewardedVideoAd = null
// 激励视频id
let rewardedVideoAdId = 'adunit-420f9f71f25daab8';
// 是否观看了激励视频
let watchRewardedVideo = false;
// 音频前缀
var audioPrefix = "audio/";

Page({

    /**
     * 页面的初始数据
     */
    data: {
        lock: false,
        finish: false, //是否完成
        disabled: false, //是否禁用
        defaultSize: 'default',
        primarySize: 'default',
        warnSize: 'default',
        longitude: "",
        latitude: "",
        markers: [],
        polyline: [],
        runningTime:"",
        timer: null,
    },


    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        var now = new Date();
        console.log(now);
        wx.authorize({
            scope: 'scope.userLocationBackground'
        })
        if (wx.createRewardedVideoAd) {
            rewardedVideoAd = wx.createRewardedVideoAd({
                adUnitId: rewardedVideoAdId
            })
            rewardedVideoAd.onLoad(() => {
                console.log('onLoad event emit')
            })
            rewardedVideoAd.onError((err) => {
                console.log('onError event emit', err)
            })
            rewardedVideoAd.onClose((res) => {
                console.log('onClose event emit', res)
                // 用户点击了【关闭广告】按钮
                if (res && res.isEnded) {
                    // 正常播放结束，可以下发游戏奖励
                    console.log("正常播放结束，可以下发游戏奖励");
                    watchRewardedVideo = true;
                    this.startRun();
                } else {
                    // 播放中途退出，不下发游戏奖励
                    console.log("播放中途退出，不下发游戏奖励");
                }
            })
        }
        //wx.openSetting();
        this.wxGetLocation();
        wx.updateShareMenu({
            withShareTicket: true,
            success() {}
        })
        wx.showShareMenu({
            withShareTicket: true,
            menus: ['shareAppMessage', 'shareTimeline']
        })
        // 保持屏幕常亮
        wx.setKeepScreenOn({

            keepScreenOn: true

        })
    },
    /**
     * 开始跑步
     * @param {点击开始跑步事件} e 
     */
    startRun: function (e) {

        var that = this

        if (mustWatchAd) {
            if (watchRewardedVideo) {
                this.doStartRun();
            } else {
                wx.showModal({
                    title: '提示',
                    content: '请观看激励视频广告,广告后一个月内可以无限次使用',
                    success(res) {
                        if (res.confirm) {
                            console.log('用户点击确定')
                            wx.openSetting({
                                success: (res) => {
                                    console.log(res)
                                    // 用户触发广告后，显示激励视频广告
                                    if (rewardedVideoAd) {
                                        rewardedVideoAd.show().catch(() => {
                                            // 失败重试
                                            rewardedVideoAd.load()
                                                .then(() => rewardedVideoAd.show())
                                                .catch(err => {
                                                    console.error('激励视频 广告显示失败', err)
                                                })
                                        })
                                    }
                                },
                            })
                        } else if (res.cancel) {
                            console.log('用户点击取消')
                        }
                    }

                })

            }
        } else {
            this.doStartRun();

        }



    },
    doStartRun() {
        var that = this;
        // 可以通过 wx.getSetting 先查询一下用户是否授权了 "scope.userLocationBackground" 这个 scope
        wx.getSetting({
            success(res) {
                console.log(res);
                if (!res.authSetting['scope.userLocationBackground']) {
                    wx.authorize({
                        scope: 'scope.userLocationBackground',
                        success() {},
                        fail(res) {
                            wx.showModal({
                                title: '提示',
                                content: '授权失败，点击右上角设置位置为"使用小程序时和离开后允许"',
                                success(res) {
                                    if (res.confirm) {
                                        console.log('用户点击确定')
                                        wx.openSetting({
                                            success: (res) => {
                                                console.log(res)
                                            },
                                        })
                                    } else if (res.cancel) {
                                        console.log('用户点击取消')
                                    }
                                }

                            })
                        }
                    })
                } else {
                    var startTime = new Date().getTime();
                    that.getRunningTime(startTime);
                    that.setData({
                        disabled: true,
                        finish: false
                    });
                    wx.showToast({
                        title: '成功',
                        icon: 'succes',
                        duration: 3000,
                        mask: true
                    });
                    // 用户已经同意小程序使用录音功能，后续调用 wx.wxStartLocationUpdateBackground 接口不会弹窗询问
                    // 设置音频资源
                    innerAudioContext.src = audioPrefix + "start.mp3";
                    innerAudioContext.play();
                    innerAudioContext.onEnded(res => {
                        console.log("播放结束")
                        that.wxStartLocationUpdateBackground();
                    })

                }
            },
            fail(res) {
                console.log(res)
            }
        })
    },
    /**
     * 跑步完成
     * @param {跑步完成} e 
     */
    finishRun: function (e) {
        clearInterval(this.data.timer);
        this.loadAminate();
        distancePoints = [];
        points = [];
        runningDistance = 0;
        playedDistances = [];
        var that = this
        innerAudioContext.src = audioPrefix + "/finish.mp3";
        that.playAudio();
        this.setData({
            disabled: false,
            finish: true
        })

        wx.showToast({
            title: '成功',
            icon: 'succes',
            duration: 3000,
            mask: true
        });
        wx.stopLocationUpdate({
            success(res) {
                console.log('stopLocationUpdate success res:', res)
            },
            fail(res) {
                console.log('stopLocationUpdate fail res:', res)
            }
        });
    },
    /**
     * 后台更新位置
     */
    wxStartLocationUpdateBackground() {
        wx.startLocationUpdateBackground({
            success: (res) => {
                console.log("startLocationUpdateBackground调用成功", res);
                if (!this.finish) {
                    // 必须有
                    wx.onLocationChange((_res) => {
                        console.log(_res)
                        this.setMapData(_res.longitude, _res.latitude);
                        this.wxGetLocation();
                    })

                }
            },
            fail(res) {
                console.log("startLocationUpdateBackground调用失败", res);
            }
        });
    },


    /**
     * 获取位置
     */
    wxGetLocation() {
        var that = this
        wx.getLocation({
            isHighAccuracy: true,
            type: 'gcj02',
            success(res) {
                console.log("getLocation调用成功", res)
                const latitude = res.latitude
                const longitude = res.longitude
                const speed = res.speed
                const accuracy = res.accuracy
                that.setMapData(longitude, latitude);

            },
            fail(res) {
                console.log("getLocation调用失败", res)
            }
        })
    },
    /**
     * 设置地图数据
     * @param {经度} longitude 
     * @param {纬度} latitude 
     */
    setMapData(longitude, latitude) {
        this.caculateRunningDistance(longitude, latitude);

    },

    /**
     * 加载动画
     */
    loadAminate() {
        var markers =  this.data.markers;
        console.log(markers);
        console.log(markers.length);
        for (var i = 0; i < markers.length; i++) {
            if (i != markers.length) {
                console.log(markers[i]);
                mapContext.translateMarker({
                    markerId: i,
                    destination: {
                        longitude: markers[i + 1].longitude,
                        latitude: markers[i + 1].latitude
                    },
                    autoRotate: false,
                    rotate: 0,
                    duration: 100,
                    animationEnd(res) {
                        console.log("animationEnd")

                    },
                    success(res) {
                        console.log("success")

                    },
                    fail() {
                        console.log("fail")

                    },
                    complete(res) {
                        console.log("complete")

                    }
                })
            }
        }

    },


    /**
     * 计算跑步距离
     * @param {经度} longitude 
     * @param {纬度} latitude 
     */
    caculateRunningDistance(longitude, latitude) {
        var that = this;
        var jwd = {};
        jwd.longitude = longitude;
        jwd.latitude = latitude;
        if (points.length < 2) {
            // 如果坐标小于2,则绘制轨迹会报错
            points.push(jwd);
        }
        if (distancePoints.length === 0) {
            distancePoints.push(jwd);
        }


        console.log("你已经跑了:", runningDistance, "米")
        console.log("distancePoints.length", distancePoints.length)
        console.log("points.length", points.length)
        console.log("distancePoints:", distancePoints)
        if (!!longitude && !!latitude && distancePoints.length >= 1) {
            // 1.取最后一个元素
            let lastPoint = points[points.length - 1];
            console.log("lastPoint", lastPoint);
            console.log("lastPoint.longitude === longitude", lastPoint.longitude === longitude)
            console.log("lastPoint.latitude === latitude", lastPoint.latitude === latitude)
            // 位置发生了变化或者是首次进入小程序
            if (!(lastPoint.longitude === longitude && lastPoint.latitude === latitude) || distancePoints.length==1) {
                console.log("位置发生了变化或者首次进入小程序")
                var jwd = {};
                jwd.longitude = longitude;
                jwd.latitude = latitude;
                distancePoints.push(jwd);


                points.push(jwd)
                let marker = [{
                    id: index,
                    longitude: longitude,
                    latitude: latitude,
                    iconPath: "../../images/running.png",
                    width: 50,
                    height: 50
                }];
                console.log(points)
                let polyline = [{
                    points: points,
                    color: "#FF0000DD",
                    width: 2,
                    dottedLine: false
                }];
                this.setData({
                    longitude: longitude,
                    latitude: latitude,
                    markers: marker,
                    polyline: polyline
                })
                index++;

                // 2.计算距离 
                var distance = this.calculateDistance(latitude, longitude, lastPoint.latitude, lastPoint.longitude);
                console.log("又跑了", distance)


                // 3.总的跑步距离
                //runningDistance += distance;
                runningDistance += distance * 10;
                console.log("总共跑步", runningDistance);
                that.setData({
                    runningDistance: runningDistance
                })
                // 4.播放音频并将播放记录存入
                let lastPlayedDistance = playedDistances[playedDistances.length - 1];
                console.log("lastPlayedDistance", lastPlayedDistance)
                // 求整百
                var runningDistanceHundred = this.floorToNearestHundred(runningDistance);
                console.log("runningDistanceHundred", runningDistanceHundred);
                if (!!lastPlayedDistance) {
                    console.log("上次播放的存在")
                    // 存在
                    if (lastPlayedDistance != runningDistanceHundred) {
                        console.log("没有播放过")
                        //innerAudioContext.src = audioPrefix + 距离 + ".mp3"
                        innerAudioContext.src = audioPrefix + runningDistanceHundred + ".mp3";
                        innerAudioContext.play() // 播放
                        playedDistances.push(runningDistanceHundred);
                    } else {
                        console.log("已经播放过,不再重复播放")
                    }

                } else {
                    // 第一次播放
                    console.log("第一次播放,是否能播放取决于距离是否大于100米")
                    if (runningDistanceHundred >= 100) {
                        console.log("跑步距离大于等于100米")
                        //innerAudioContext.src = audioPrefix + 距离 + ".mp3"
                        innerAudioContext.src = audioPrefix + runningDistanceHundred + ".mp3";
                        innerAudioContext.play() // 播放
                        playedDistances.push(runningDistanceHundred);
                    } else {
                        console.log("跑步距离小于100米");
                        this.playTip();

                    }

                }
            } else {
                console.log("位置没有变化")
                this.playTip();
            }



        } else {
            console.log("没有数据");
        }
    },

    getRandomElement(arr) {
        if (!Array.isArray(arr) || arr.length === 0) return undefined;
        const randomIndex = Math.floor(Math.random() * arr.length);
        return arr[randomIndex];
    },
    /**
     * 播放提示语言
     */
    playTip() {
        var now = new Date().getTime();
        if (now > lastTipPlayTime + tipPlayCyclePeriord) {
            var tipMp3 = this.getRandomElement(runningTips);
            if (!!tipMp3) {
                console.log("提示语音文件为", tipMp3)
                console.log("播放跑步提示语音")
                innerAudioContext.src = audioPrefix + tipMp3;
                innerAudioContext.play() // 播放
                lastTipPlayTime = now;
            }
        } else {
            console.log("tip未达到播放间隔,不播放tip")
        }


    },
    /**
     * 数字向下取整百
     * @param {数字} num 
     */
    floorToNearestHundred(num) {
        return Math.floor(num * 0.01) * 100;
    },
    /**
     * 播放音频
     * @param {音频资源} audioSrc 
     */
    playAudio() {
        innerAudioContext.play() // 播放
        //innerAudioContext.destroy() // 释放音频资源
    },
    /**
     * 根据经纬度计算距离(单位:米)
     * @param {第一个坐标纬度} lat1 
     * @param {第一个坐标经度} lon1 
     * @param {第二个坐标纬度} lat2 
     * @param {第二个坐标经度} lon2 
     */
    calculateDistance(lat1, lon1, lat2, lon2) {
        const radians = Math.PI / 180;
        const R = 6371; // 地球半径，单位为公里

        const deltaLat = (lat2 - lat1) * radians;
        const deltaLon = (lon2 - lon1) * radians;

        lat1 = lat1 * radians;
        lat2 = lat2 * radians;

        const a = Math.sin(deltaLat / 2) * Math.sin(deltaLat / 2) +
            Math.cos(lat1) * Math.cos(lat2) *
            Math.sin(deltaLon / 2) * Math.sin(deltaLon / 2);
        const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
        const distance = R * c;

        return distance.toFixed(3) * 1000;
    },
    /**
     * 获取时间差
     * @param {*} endTime 
     */
    getRunningTime(startTime) {
        console.log("getRunningTime start");
        var that = this;
        var timer = setInterval(function () {
            const now = new Date().getTime();
            const distance = now - startTime ;

            const days = Math.floor(distance / (1000 * 60 * 60 * 24));
            const hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
            const minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
            const seconds = Math.floor((distance % (1000 * 60)) / 1000);

            var runningTime = days + "天 " + hours + "小时 " +
                minutes + "分钟 " + seconds + "秒 ";

                that.setData({
                    runningTime: runningTime 
                })
            console.log("runningTime",runningTime)
        }, 1000);
        that.setData({
            timer: timer
        });
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {


    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {
        const promise = new Promise(resolve => {
            setTimeout(() => {
                resolve({
                    title: '健康跑步'
                })
            }, 2000)
        })
        return {
            title: '健康跑步',
            path: '/page/running/running',
            promise
        }
    }
})